#include <iostream>
#include <mutex>
#include<unistd.h>
#include<pthread.h>
#include "Mutex.hpp"

using namespace MutexModule;

int ticket = 1000;
//pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;
//std::mutex cpp_lock;


class ThreadData
{
public:
    ThreadData(const std::string &n, Mutex &lock)
        : name(n), lockp(&lock)
    {
    }

    ~ThreadData()
    {
    }

    std::string name;
    Mutex *lockp;
};

void *routine(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (1)
    {
        LockGuard guard(*td->lockp);
        //cpp_lock.lock();
        //pthread_mutex_lock(td->lockp);
        //pthread_mutex_lock(&glock)
        //td->lockp->Lock()

        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
            ticket--;

            //cpp_lock.unlock();
            //pthread_mutex_unlock(td->lockp);
            //pthread_mutex_unlock(&glock);
            //td->lockp->Unlock();
        }
        else
        {
            //cpp_lock.unlock();
            //pthread_mutex_unlock(td->lockp);
            //pthread_mutex_unlock(&glock);
            //td->lockp->Unlock();

            break;
        }
    }

    return nullptr;
}

int main()
{
    Mutex lock;
    pthread_t t1, t2, t3, t4;

    ThreadData *td1 = new ThreadData("thread-1", lock);
    pthread_create(&t1, nullptr, routine, td1);

    ThreadData *td2 = new ThreadData("thread-2", lock);
    pthread_create(&t2, nullptr, routine, td2);

    ThreadData *td3 = new ThreadData("thread-3", lock);
    pthread_create(&t3, nullptr, routine, td3);

    ThreadData *td4 = new ThreadData("thread-4", lock);
    pthread_create(&t4, nullptr, routine, td4);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    

    return 0;
}